package com.bwie.conferenceroom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.MeetingScheduling;
import com.bwie.common.domain.Occupation;
import com.bwie.common.domain.SysUser;
import com.bwie.common.domain.response.MeetingSchedulingRes;
import com.bwie.common.utils.JwtUtils;
import com.bwie.conferenceroom.mapper.MeetingSchedulingMapper;
import com.bwie.conferenceroom.service.MeetingSchedulingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class MeetingSchedulingServiceImpl implements MeetingSchedulingService {
    @Autowired
    private MeetingSchedulingMapper meetingSchedulingMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取会议室预约列表
     * @return
     */
    @Override
    public List<MeetingSchedulingRes> getMeetingSchedulingList() {
        return meetingSchedulingMapper.getMeetingSchedulingList();
    }

    /**
     * 新增/修改预定会议室
     * @param meetingScheduling
     */
    @Override
    public void saveOrUpdMeetingScheduling(MeetingScheduling meetingScheduling) {
        //获取登录人信息
        SysUser sysUser = userInfo();
        meetingScheduling.setUserId(sysUser.getId());
        if (meetingScheduling.getId()!=null){
            //修改预定会议室
            meetingSchedulingMapper.updMeetingScheduling(meetingScheduling);
        }else {
            //新增预定会议室
            meetingSchedulingMapper.addMeetingScheduling(meetingScheduling);
            //新增会议室占用
            Occupation occupation = new Occupation();
            occupation.setOccupationTime(meetingScheduling.getMeetingTime());
            occupation.setConferenceRoomId(meetingScheduling.getConferenceRoomId());
            occupation.setUserId(sysUser.getId());
            meetingSchedulingMapper.addOccupation(occupation);
        }
    }

    /**
     * 删除预定会议室
     * @param id
     */
    @Override
    public void delMeetingScheduling(Integer id) {
        meetingSchedulingMapper.delMeetingScheduling(id);
    }

    /**
     * 获取登录人信息
     * @return
     */
    private SysUser userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String s = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        SysUser sysUser = JSONObject.parseObject(s, SysUser.class);
        return sysUser;
    }
}
